package com.smec.remes.module.query.picture;

import android.app.ProgressDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.blankj.utilcode.util.SizeUtils;
import com.google.gson.Gson;
import com.smec.moblie.R;
import com.smec.moblie.databinding.FragmentPictureBinding;
import com.smec.remes.base.SmecBaseFragment;
import com.smec.remes.bean.query.ClassType;
import com.smec.remes.bean.query.ClassTypeResponse;
import com.smec.remes.bean.query.ElevatorType;
import com.smec.remes.bean.query.ElevatorTypeResponse;
import com.smec.remes.bean.query.ListQueryPicture;
import com.smec.remes.module.query.picture.adapter.SmecPictureAdapter;
import com.smec.remes.module.submit.SmecSubmitPresenter;
import com.smec.remes.util.CommonUtils;
import com.smec.remes.util.ExtractNumber;
import com.smec.remes.util.GetFullUrl;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zyyoona7.lib.EasyPopup;
import com.zyyoona7.lib.HorizontalGravity;
import com.zyyoona7.lib.VerticalGravity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/1/4.
 */

public class SmecPictureFragment extends SmecBaseFragment<SmecSubmitPresenter> {

    private FragmentPictureBinding fragmentPictureBinding;
    private SmecPictureAdapter smecPictureAdapter;
    private String _url="getMatnrImage/getMatnrImageService";
    private String ELEVATOR_TYPE = "getEleType/getEleTypeService";
    private String CLASS_TYPE = "getMatnrClass/getMatnrClassService";
    private String type="elevatorType";
    private Gson gson=new Gson();
    private EasyPopup mCirclePop;
    private ProgressDialog progressDialog;
    private List<Map<String, Object>> data_list;
    private SimpleAdapter sim_adapter;
    private ArrayList<String> eleTypeListResponse=new ArrayList<>();
    private ArrayList<String> eleTypeList=new ArrayList<>();
    private ArrayList<String> classListResponse=new ArrayList<>();
    private ArrayList<String> classList=new ArrayList<>();
    private String [] from ={"text"};
    private int [] to = {R.id.text};
    private int ele=0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentPictureBinding=DataBindingUtil.inflate(inflater, R.layout.fragment_picture,container,false);
        smecPictureAdapter=new SmecPictureAdapter(getActivity());
        fragmentPictureBinding.pictureRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        fragmentPictureBinding.pictureRecyclerView.setAdapter(smecPictureAdapter);
        data_list = new ArrayList<Map<String, Object>>();
        _elevatorType();
        _choiceUse();
        _search();
        _return();
        girdOnclick();
        return fragmentPictureBinding.getRoot();
    }

    public void _return(){
        fragmentPictureBinding.llReOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentPictureBinding.spinner.setText("梯种");
                fragmentPictureBinding.llMantr.setVisibility(View.GONE);
                fragmentPictureBinding.llHeading.setVisibility(View.GONE);
                fragmentPictureBinding.tvLadder.setText("梯种");
                fragmentPictureBinding.tvHeading.setText("品目号");
                fragmentPictureBinding.edSearch.setText("");
                fragmentPictureBinding.llPicture.setVisibility(View.GONE);
                fragmentPictureBinding.llLeftRight.setVisibility(View.VISIBLE);
                fragmentPictureBinding.gridview.setVisibility(View.VISIBLE);
                fragmentPictureBinding.gridview2.setVisibility(View.GONE);
                data_list.clear();
                getData(eleTypeListResponse);
                sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.gridview_item,from,to);
                fragmentPictureBinding.gridview.setAdapter(sim_adapter);
            }
        });
        fragmentPictureBinding.llHeading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentPictureBinding.spinner.setText("品目");
                fragmentPictureBinding.llMantr.setVisibility(View.GONE);
                fragmentPictureBinding.tvHeading.setText("品目号");
                fragmentPictureBinding.edSearch.setText("");
                fragmentPictureBinding.llPicture.setVisibility(View.GONE);
                fragmentPictureBinding.llLeftRight.setVisibility(View.VISIBLE);
                fragmentPictureBinding.gridview2.setVisibility(View.VISIBLE);
                fragmentPictureBinding.gridview.setVisibility(View.GONE);
                data_list.clear();
                getData(classListResponse);
                sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.gridview_item,from,to);
                fragmentPictureBinding.gridview2.setAdapter(sim_adapter);
            }
        });
    }

    public void _search(){
        fragmentPictureBinding.ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fragmentPictureBinding.edSearch.setText("");
            }
        });
        fragmentPictureBinding.edSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                fragmentPictureBinding.ivDelete.setVisibility(View.VISIBLE);
            }
        });
        fragmentPictureBinding.ivSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                _Search();
            }
        });

        fragmentPictureBinding.edSearch.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_ENTER) {
                            _Search();
                        }
                        return false;
                    }
                });

    }

    public void _Search(){
        if(TextUtils.isEmpty(fragmentPictureBinding.edSearch.getText())){
            Toast.makeText(getActivity(),"请输入信息",Toast.LENGTH_SHORT).show();
        }else {
            smecPictureAdapter.clearList();
            CommonUtils.hideImmManager(fragmentPictureBinding.getRoot());
            fragmentPictureBinding.llReOne.setVisibility(View.VISIBLE);
            fragmentPictureBinding.llHeading.setVisibility(View.VISIBLE);
            fragmentPictureBinding.llMantr.setVisibility(View.VISIBLE);
            fragmentPictureBinding.llLeftRight.setVisibility(View.GONE);
            fragmentPictureBinding.llPicture.setVisibility(View.VISIBLE);
            if(progressDialog == null){
                progressDialog=new ProgressDialog(getActivity());
            }
            progressDialog.setMessage("正在上传.....");
            progressDialog.show();
            Map map = new HashMap();
            if(type.equals("elevatorType")){
                map.put("elevatorType",_setHashMap(fragmentPictureBinding.edSearch.getText().toString()));  //梯种
            }else {
                map.put("elevatorType","");  //梯种
            }
            if(type.equals("class")){
                map.put("class",_setHashMap(fragmentPictureBinding.edSearch.getText().toString()));   //品目
            }else {
                map.put("class","");   //品目
            }

            if (type.equals("matnr")){
                map.put("matnr",_setHashMap(fragmentPictureBinding.edSearch.getText().toString()));   //物料号
            }else {
                map.put("matnr","");   //物料号
            }


            map.put("pageNum","1");
            map.put("pageSize","30");
            String adress= GetFullUrl.getFullUrl(_url,map);
            Log.w("URL", GetFullUrl.getFullUrl(_url,map));
            OkHttpUtils.get().url(adress).build().execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    progressDialog.dismiss();
                }

                @Override
                public void onResponse(String response, int id) {
                    progressDialog.dismiss();
                    ListQueryPicture listQueryPicture=gson.fromJson(response.toString().trim(),ListQueryPicture.class);
                    if(CommonUtils.notEmpty(listQueryPicture.getMatnrList())){
                        smecPictureAdapter.setArrayList(listQueryPicture.getMatnrList());
                    }
                }
            });
            fragmentPictureBinding.tvLadder.setText("梯种");
            fragmentPictureBinding.tvHeading.setText("品目号");
        }
    }

    public String _setHashMap(String b){
        if(TextUtils.isEmpty(b)){
            return "";
        }else {
            return b;
        }
    }

    /**
     * GirdView列表点击事件
     */

    public void girdOnclick() {
        fragmentPictureBinding.gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                fragmentPictureBinding.tvLadder.setText(data_list.get(i).get("text").toString());
                ele=i;
                _classtype(eleTypeList.get(i));
                data_list.clear();
                type="class";
            }
        });

        fragmentPictureBinding.gridview2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                fragmentPictureBinding.tvHeading.setText(ExtractNumber._getNum(data_list.get(i).get("text").toString()));
                _getMsg();
                data_list.clear();
                type="matnr";
            }
        });
    }

    /**
     * 获取梯种列表
     */
    public void _elevatorType(){
        fragmentPictureBinding.spinner.setText("梯种");
        fragmentPictureBinding.edSearch.setHint("请输入梯种");
        fragmentPictureBinding.edSearch.setText("");
        String adress= GetFullUrl.getFullUrl(ELEVATOR_TYPE,null);
        OkHttpUtils.get().url(adress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ElevatorTypeResponse elevatorTypeResponse=gson.fromJson(response.toString(),ElevatorTypeResponse.class);
                if(CommonUtils.notEmpty(elevatorTypeResponse.getEleTypeList())){
                    ArrayList<ElevatorType> elevatorTypeArrayList=new ArrayList<>();
                    ElevatorType elevatorType=new ElevatorType();
                    for(int i=0;i<elevatorTypeResponse.getEleTypeList().size();i++){
                        elevatorTypeArrayList.add(elevatorTypeResponse.getEleTypeList().get(i));
                        eleTypeListResponse.add(elevatorTypeResponse.getEleTypeList().get(i).getEleTypeMeaning());
                        eleTypeList.add(elevatorTypeResponse.getEleTypeList().get(i).getEleType());
                    }
                }
                getData(eleTypeListResponse);
                sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.gridview_item,from,to);
                fragmentPictureBinding.gridview.setAdapter(sim_adapter);
            }
        });
    }

    /**
     *  获取品目列表
     */
    public void _classtype(String elevatorType){
        fragmentPictureBinding.spinner.setText("品目号");
        fragmentPictureBinding.edSearch.setHint("请输入品目号");
        fragmentPictureBinding.edSearch.setText("");
        fragmentPictureBinding.llHeading.setVisibility(View.VISIBLE);
        fragmentPictureBinding.gridview.setVisibility(View.GONE);
        fragmentPictureBinding.gridview2.setVisibility(View.VISIBLE);
        Map map = new HashMap();
        map.put("elevatorType",elevatorType);
        String adress= GetFullUrl.getFullUrl(CLASS_TYPE,map);
        OkHttpUtils.get().url(adress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ClassTypeResponse classTypeResponse=gson.fromJson(response.toString(),ClassTypeResponse.class);
                if(CommonUtils.notEmpty(classTypeResponse.getClassList())){
                    classListResponse.clear();
                    ArrayList<ClassType> classTypeArrayList=new ArrayList<>();
                    for(int i=0;i<classTypeResponse.getClassList().size();i++){
                        classTypeArrayList.add(classTypeResponse.getClassList().get(i));
                        classList.add(classTypeResponse.getClassList().get(i).getClassType());
                        classListResponse.add(classTypeResponse.getClassList().get(i).getClassType()+classTypeResponse.getClassList().get(i).getClassMeaning()+"部件");
                    }
                }
                getData(classListResponse);
                sim_adapter = new SimpleAdapter(getActivity(), data_list, R.layout.gridview_item,from,to);
                fragmentPictureBinding.gridview2.setAdapter(sim_adapter);
            }
        });
    }

    /**
     *  获取物料列表
     */
    public void _getMsg(){
        smecPictureAdapter.clearList();
        fragmentPictureBinding.spinner.setText("物料号");
        fragmentPictureBinding.edSearch.setHint("请输入物料号");
        fragmentPictureBinding.edSearch.setText("");
        fragmentPictureBinding.llLeftRight.setVisibility(View.GONE);
        fragmentPictureBinding.llPicture.setVisibility(View.VISIBLE);
        fragmentPictureBinding.llMantr.setVisibility(View.VISIBLE);
        Map map = new HashMap();
        map.put("elevatorType",eleTypeList.get(ele));  //梯种
        map.put("class", ExtractNumber._getNum(fragmentPictureBinding.tvHeading.getText().toString()));   //品目
        map.put("matnr","");   //物料号
        map.put("pageNum","1");
        map.put("pageSize","30");
        String adress= GetFullUrl.getFullUrl(_url,map);
        Log.w("URL", GetFullUrl.getFullUrl(_url,map));
        OkHttpUtils.get().url(adress).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) { 
                ListQueryPicture listQueryPicture=gson.fromJson(response.toString().trim(),ListQueryPicture.class);
                if(CommonUtils.notEmpty(listQueryPicture.getMatnrList())){
                    smecPictureAdapter.setArrayList(listQueryPicture.getMatnrList());
                }
            }
        });
    }

    /**
     * 下拉列表
     */
    public void _choiceUse(){
        fragmentPictureBinding.llChoiceUse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPopupWindow(fragmentPictureBinding.llChoiceUse);
            }
        });
    }

    private void showPopupWindow(View view){
        mCirclePop = new EasyPopup(getActivity())
                .setContentView(R.layout.layout_choice_type)
                .setAnimationStyle(R.style.QQPopAnim)
                //是否允许点击PopupWindow之外的地方消失
                .setFocusAndOutsideEnable(true)
                //变暗的透明度(0-1)，0为完全透明
                .setDimValue(0.4f)
                //指定任意 ViewGroup 背景变暗
                .createPopup();
        mCirclePop.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.LEFT, SizeUtils.dp2px(74), 0);
        LinearLayout smecCompare=mCirclePop.getView(R.id.smec_compare);
        smecCompare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCirclePop.dismiss();
                fragmentPictureBinding.spinner.setText("梯种");
                fragmentPictureBinding.edSearch.setHint("请输入梯种");
                if(!fragmentPictureBinding.tvLadder.getText().equals("梯种")){
                    fragmentPictureBinding.edSearch.setText(fragmentPictureBinding.tvLadder.getText());
                }else {
                    fragmentPictureBinding.edSearch.setText("");
                }
                type="elevatorType";
            }
        });
        LinearLayout smecDraft=mCirclePop.getView(R.id.smec_draft);
        smecDraft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCirclePop.dismiss();
                fragmentPictureBinding.spinner.setText("品目号");
                fragmentPictureBinding.edSearch.setHint("请输入品目号");
                if(!fragmentPictureBinding.tvHeading.getText().equals("品目号")){
                    fragmentPictureBinding.edSearch.setText(fragmentPictureBinding.tvHeading.getText());
                }else {
                    fragmentPictureBinding.edSearch.setText("");
                }
                type="class";
            }
        });
        LinearLayout smecNote=mCirclePop.getView(R.id.smec_notes);
        smecNote.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCirclePop.dismiss();
                fragmentPictureBinding.spinner.setText("物料号");
                fragmentPictureBinding.edSearch.setHint("请输入物料号");
                fragmentPictureBinding.edSearch.setText("");
                type="matnr";
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        fragmentPictureBinding.edSearch.setText("");
    }

    public List<Map<String, Object>> getData(ArrayList<String> list){
        for(int i=0;i<list.size();i++){
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("text",list.get(i));
            data_list.add(map);
        }
        return data_list;
    }

    @Override
    protected SmecSubmitPresenter getPersenter() {
        return null;
    }

    public static SmecPictureFragment newInstance() {
        Bundle args = new Bundle();
        SmecPictureFragment fragment = new SmecPictureFragment();
        fragment.setArguments(args);
        return fragment;
    }
}
